<template>
  <div>
    <h2>文章管理</h2>
    <el-card>
      <div class="toolbar">
        <el-button type="primary" @click="createArticle">➕ 新建文章</el-button>
      </div>
      <el-table :data="articles" border style="width: 100%">
        <el-table-column prop="author" label="账号" />
        <el-table-column label="标题">
          <template #default="{ row }">
            <span class="link" @click="goDetail(row.id)">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签">
          <template #default="{ row }">
            <el-tag
              v-for="tag in limitedTags(row.tags)"
              :key="tag"
              type="success"
              size="small"
              class="tag-item"
            >
                {{ tag.name }}
            </el-tag>
            <span v-if="row.tags.length > 3" class="tag-more" @click="openTagDialog(row.tags)">
              +{{ row.tags.length - 3 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="内容摘要">
          <template #default="{ row }">
            {{ plainText(row.content) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="edit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="tagDialogVisible" title="全部标签" width="400px" :lock-scroll="false">
      <div class="tag-dialog-body">
        <el-tag
          v-for="tag in tagDialogTags"
          :key="tag"
          type="info"
          size="default"
          class="tag-item"
        >
          {{ tag }}
        </el-tag>
      </div>
      <template #footer>
        <el-button @click="tagDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import removeMd from 'remove-markdown'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import * as articleApi from '@/api/article'

interface Tag {
  id: number
  name: string
}

interface Article {
  id: number
  title: string
  author: string
  content: string
  tags: Tag[]
}

const router = useRouter()
const userStore = useUserStore()

const articles = ref<Article[]>([])

const tagDialogVisible = ref(false)
const tagDialogTags = ref<string[]>([])

function limitedTags(tags: string[]) {
  return tags.slice(0, 3)
}

function openTagDialog(tags: string[]) {
  tagDialogTags.value = tags
  tagDialogVisible.value = true
}

function plainText(md: string): string {
  const text = removeMd(md || '').replace(/\n/g, ' ')
  return text.length > 50 ? text.slice(0, 50) + '...' : text
}

function confirmDelete(article: Article) {
  ElMessageBox.confirm(`确定要删除《${article.title}》吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteArticle(article.id)
    })
    .catch(() => {})
}

async function deleteArticle(id: number) {
  try {
    const res = await articleApi.deleteArticle(id)
    if (res.code === 0) {
      articles.value = articles.value.filter(a => a.id !== id)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e) {
    ElMessage.error('网络错误，删除失败')
  }
}
const emit = defineEmits(['create', 'edit', 'delete', 'detail'])
function edit(row: Article) {
  emit('edit', row)  // 触发事件告诉父组件“要编辑哪个文章”
}

function createArticle() {
  emit('create')    // 触发事件告诉父组件“要新建文章”
}

function goDetail(id: number) {
  if (!id) {
    console.warn('无效文章id，无法跳转')
    return
  }
  router.push({ name: 'ArticleDetail', params: { id } })
}

// 初始化加载当前用户文章
async function fetchMyArticles() {
  if (!userStore.userInfo.id) return
  try {
    const res = await articleApi.getArticlesByUser(userStore.userInfo.id)
    if (res.code === 0 && Array.isArray(res.data)) {
      articles.value = res.data
    } else {
      ElMessage.warning(res.message || '文章加载失败')
    }
  } catch (e) {
    ElMessage.error('网络或服务器错误')
  }
}

onMounted(() => {
  fetchMyArticles()
})
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
.tag-item {
  margin-right: 4px;
  margin-bottom: 4px;
}
.tag-more {
  color: #409EFF;
  cursor: pointer;
  font-size: 12px;
  margin-left: 6px;
  user-select: none;
}
.tag-dialog-body {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.link {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
}
</style>
